package com.ady.webmgic.util;/**
 * Created by pc on 2017/12/13 0013.
 */

import com.ady.util.FrameUtil;
import com.ady.webmgic.KuaidailiProxyProvider;

import java.io.IOException;
import java.io.InputStream;

/**
 * <b>description</b>：快代理工具类 <br>
 * <b>time</b>：2017-12-13 17:39 <br>
 * <b>author</b>： ready likun_557@163.com
 */
public class KuaidailiUtil {
    /**
     * kuaidaili.apiurl=${kuaidaili.apiurl}
     * kuaidaili.username=${kuaidaili.username}
     * kuaidaili.password=${kuaidaili.password}
     */
    private volatile static String properties_file;
    public static Object properties_lock = new Object();
    public static final String PROPERTIES_FILE = "kuaidaili.properties";
    public static final String PROPERTIES_DEFAULT_FILE = "kuaidaili_default.properties";
    private static final String APIURL_KEY = "kuaidaili.apiurl";
    private static final String USERNAME_KEY = "kuaidaili.username";
    private static final String PASSWORD_KEY = "kuaidaili.password";

    private static String getPropertiesFile() throws IOException {
        if (properties_file == null) {
            synchronized (properties_lock) {
                if (properties_file == null) {
                    String file = PROPERTIES_DEFAULT_FILE;
                    InputStream inputStream = KuaidailiUtil.class.getClassLoader().getResourceAsStream(PROPERTIES_DEFAULT_FILE);
                    if (inputStream == null) {
                        file = PROPERTIES_FILE;
                    }
                    properties_file = file;
                }
            }
        }
        return properties_file;
    }

    /**
     * 获取代理api地址
     *
     * @return
     * @throws IOException
     */
    public static String getApiurl() throws IOException {
        return FrameUtil.getResourceByFile(getPropertiesFile(), APIURL_KEY);
    }

    /**
     * 获取代理username
     *
     * @return
     * @throws IOException
     */
    public static String getUsername() throws IOException {
        return FrameUtil.getResourceByFile(getPropertiesFile(), USERNAME_KEY);
    }

    /**
     * 获取代理密码
     *
     * @return
     * @throws IOException
     */
    public static String getPassword() throws IOException {
        return FrameUtil.getResourceByFile(getPropertiesFile(), PASSWORD_KEY);
    }

    public static KuaidailiProxyProvider getProxyProvider() {
        try {
            return KuaidailiProxyProvider.getInstance(getApiurl(), getUsername(), getPassword());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

}
